<template>
    <div>
        <span class="title1">房源分配 /</span>
        <span class="title2">开始分配</span>
        <div class="container">
            <div class="card-container1">
                <el-card>
                    <div style="display: flex; align-items: center; margin-top: 10px">
                        <el-select v-model="query.communityId" placeholder="请选择园区" style="flex: 1">
                            <el-option
                                v-for="item in roles1"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                        <el-select v-model="query.buildingId" placeholder="请选择楼栋" style="flex: 1; margin-left: 10px">
                            <el-option
                                v-for="item in roles2"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                        <el-select v-model="query.floor" placeholder="请选择楼层" style="flex: 1; margin-left: 10px">
                            <el-option
                                v-for="item in roles3"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                        <el-button type="primary" style="margin-left: 10px;" @click="getUserList">查询</el-button>
                        <el-button plain @click="resetQuery">重置</el-button>
                    </div>
                    <el-col></el-col>
                    <el-row :gutter="10">
                        <el-col :span="4">
                        </el-col>
                        <el-col :span="4">
                        </el-col>
                        <span></span>
                    </el-row>
                    <el-table
                        @selection-change="selectChange"
                        class="table1"
                        :data="users"
                        stripe
                        style="width: 100%">
                        <el-table-column
                            label="园区"
                            prop="name">
                            <template slot-scope="scope">
                                {{scope.row.communityId}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="樓棟"
                            prop="job">
                            <template slot-scope="scope">
                                {{scope.row.buildingId}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="楼层"
                            prop="build">
                            <template slot-scope="scope">
                                {{scope.row.floor}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="房间编号"
                            prop="tel">
                            <template slot-scope="scope">
                                {{scope.row.roomId}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="床位编号"
                            prop="time">
                            <template slot-scope="scope">
                                {{scope.row.bedId}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="房间价格"
                            prop="price">
                            <template slot-scope="scope">
                                {{scope.row.price}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            prop="do"
                            width="180">
                            <template slot-scope="scope">
                                <el-button
                                    class="c"
                                    size="mini"
                                    type="text"
                                    @click="handleEdit(scope.$index, scope.row)">
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-row>
                            <el-button type="primary" style="margin-left: 1000px;">批量移动</el-button>
                        </el-row>
                    </el-table>
                </el-card>
            </div>
            <div class="card-container2">
                <el-card class="card" style="margin-top: 10px; ">
                    <div slot="header" class="clearfix"></div>
                    <!-- 本科生人数卡片 -->
                    <el-card class="sub-card1">
                        <div slot="header">
                            <span style="font-weight: 700;font-size: 16px;text-align: left;color: #fff;">本科生拥有床位</span>
<!--                            <span style="font-weight: 400;font-size: 14px;text-align: right;color: #fff;margin-left: 140px">查看名单调整</span>-->
                            <span style="width: 6.51px;height: 10.37px;color: #fff;">></span>
                        </div>
                        <div class="app"></div>
                        <div class="k1n1">
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 89px;text-align: left;color: #fff;">{{ typeABeds[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN Bold';font-weight: 700;font-size: 19px;text-align: left;color: #fff;">个</span>
                        </div>
                        <div style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">本科生正在使用床位</div>
                        <div>
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 36px;text-align: left;color: #fff;">{{ inStudent[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">个</span>
                        </div>
                    </el-card>
                    <!-- 间隔 -->
                    <div class="gap"></div>
                    <!-- 研究生人数卡片 -->
                    <el-card class="sub-card2">
                        <div slot="header">
                            <span style="font-weight: 700;font-size: 16px;text-align: left;color: #fff;">研究生拥有床位</span>
<!--                            <span style="font-weight: 400;font-size: 14px;text-align: right;color: #fff;margin-left: 140px">查看名单调整</span>-->
                            <span style="width: 6.51px;height: 10.37px;color: #fff;">></span>
                        </div>
                        <div class="app"></div>
                        <div class="k1n1">
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 89px;text-align: left;color: #fff;">{{ typeBBeds[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN Bold';font-weight: 700;font-size: 19px;text-align: left;color: #fff;">个</span>
                        </div>
                        <div style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">研究生正在使用床位</div>
                        <div>
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 36px;text-align: left;color: #fff;">{{ ingStudent[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">个</span>
                        </div>
                    </el-card>
                    <!-- 教职工人数卡片 改为博士生卡片 -->
                    <el-card class="sub-card3">
                        <div slot="header">
                            <span style="font-weight: 700;font-size: 16px;text-align: left;color: #fff;">博士生拥有床位</span>
<!--                            <span style="font-weight: 400;font-size: 14px;text-align: right;color: #fff;margin-left: 140px">查看名单调整</span>-->
                            <span style="width: 6.51px;height: 10.37px;color: #fff;">></span>
                        </div>
                        <div class="app"></div>
                        <div class="k1n1">
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 89px;text-align: left;color: #fff;">{{ typeCBeds[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN Bold';font-weight: 700;font-size: 19px;text-align: left;color: #fff;">个</span>
                        </div>
                        <div style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">博士生正在使用床位</div>
                        <div>
                            <span style="font-family: 'DIN Bold';font-weight: 700;font-size: 36px;text-align: left;color: #fff;">{{ inbStudent[0].number }}</span>
                            <span style="font-family: 'Source Han Sans CN';font-weight: 400;font-size: 14px;text-align: left;color: #fff;">个</span>
                        </div>
                    </el-card>
                </el-card></div>
        </div>
    </div>
</template>

<script>
import {url} from 'nightwatch/examples/pages/home'
import {removeUsers, userList} from '../../../../api/sixth'
import {statStudentByRole, statStudentByedu, statbed} from '../../../../api/fifth'

export default {
  name: 'Sixth',
  data: function () {
    return {
      query: {
        communityId: '',
        price: '',
        floor: '',
        roomId: '',
        buildingId: '',
        bedId: '',
        isLived: '',
        id: '',
        major: '',
        studentRole: '',
        name: ''
      },
      roles3: [{
        value: 1,
        label: '1F'
      }, {
        value: 2,
        label: '2F'
      }, {
        value: 3,
        label: '3F'
      }, {
        value: 4,
        label: '4F'
      }],
      roles2: [{
        value: 'A',
        label: 'A栋'
      }, {
        value: 'B',
        label: 'B栋'
      }, {
        value: 'C',
        label: 'C栋'
      }, {
        value: 'D',
        label: 'D栋'
      }, {
        value: 'E',
        label: 'E栋'
      }, {
        value: 'F',
        label: 'F栋'
      }],
      roles1: [{
        value: 'A',
        label: 'A园区'
      }, {
        value: 'B',
        label: 'B园区'
      }, {
        value: 'C',
        label: 'C园区'
      }, {
        value: 'D',
        label: 'D园区'
      }, {
        value: 'E',
        label: 'E园区'
      }, {
        value: 'F',
        label: 'F园区'
      }],
      value: '',
      dialogVisible: false,
      input: '',
      community: [],
      building: [],
      floors: [],
      users: [],
      // 新增数据(从隔壁平移来的)
      studentStats: [], // 用于存储处理后的数据
      rawunStudentDdata: [],
      rawinStudentData: [], // 原始数据(lived)
      unStudent: [{type: '未入住', number: 0}], // 用于存储未入住本科生的人数
      inStudent: [{type: '本科生', number: 0}], // 用于存储已入住本科生的人数
      ingStudent: [{type: '研究生', number: 0}], // 用于存储已入住研究生的人数
      inbStudent: [{type: '博士生', number: 0}], // 用于存储已入住博士生的人数
      bedsData: [{type: '研究生', number: 0}], // 用于存储从API获取的原始床位数据
      typeABeds: [{type: 'A', number: 0}], // 用于存储type=A的床位数据
      typeBBeds: [{type: 'B', number: 0}], // 用于存储type=B的床位数据
      typeCBeds: [{type: 'C', number: 0}], // 用于存储博士生的床位数据
      underBed: 0, // 用于存储本科生空闲床位
      freeBed: 0// 用于存储研究生空闲床位

    }
  },
  computed: {
    // 添加计算属性来获取本科生数量
    undergraduateCount () {
      // 假设studentStats数组中的对象有type和number属性
      return this.studentStats.reduce((sum, stat) => {
        if (stat.type === '本科生') { // 注意：这里假设type的值为“本科生”
          return sum + stat.number
        }
        return sum
      }, 0)
    }
  },
  methods: {
    selectChange (value) {
      // 这里的value就是选中的数据构成的数组
      console.info(value)
      this.selectUsers = value
    },
    resetQuery () {
      this.query.communityId = ''
      this.query.buildingId = ''
      this.query.floor = ''
      // 其他需要重置的属性也可以在这里处理
    },
    removesBtn () {
      this.$confirm('此操作将永久删除选择的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.selectUsers.map(user => user.id)
        console.info(ids)
        // 要发送数组到后端，最好用post请求
        let obj = {
          ids: ids
        }
        removeUsers(obj).then(res => {
          if (res.data === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getUserList()
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            })
          }
        })
      }).catch(() => {
      })
    },
    url () {
      return url('C:/Users/华为/Desktop/555.png')
    },
    getUserList () {
      userList(this.query).then(res => {
        this.users = res.data.records
        this.total = res.data.total
      })
    },
    async fetchAndProcessStudentStats () {
      try {
        // 同时调用两个API
        const [roleStats, eduStats] = await Promise.all([
          statStudentByRole(),
          statStudentByedu()
        ])

        // 检查响应状态
        if (roleStats.status && roleStats.code === 0 && eduStats.status && eduStats.code === 0) {
          // 合并数据并进行累加
          this.processStudentStats(roleStats.data, eduStats.data)
        }
      } catch (error) {
        console.error('Failed to fetch or process student stats:', error)
      }
    },
    processStudentStats (roleData, eduData) {
      // 初始化一个对象来存储累加的结果
      const processedStats = {}

      // 遍历roleData并累加
      roleData.forEach(item => {
        if (processedStats[item.type]) {
          processedStats[item.type] += item.number
        } else {
          processedStats[item.type] = item.number
        }
      })

      // 遍历eduData并累加（如果type已存在，则继续累加）
      eduData.forEach(item => {
        if (processedStats[item.type]) {
          processedStats[item.type] += item.number
        } else {
          // 实际上，如果eduData中有roleData中没有的type，这里也会添加它
          processedStats[item.type] = item.number
        }
      })
      // 将对象转换为数组，便于在模板中使用
      this.studentStats = Object.keys(processedStats).map(type => ({
        type,
        number: processedStats[type]
      }))
    }
  },
  async created () {
    this.getUserList()
    // 平移
    await this.fetchAndProcessStudentStats()
    try {
      statStudentByRole().then(response => {
        this.rawinStudentData = response.data // 存储原始数据
        console.log(this.rawinStudentData)
        this.inStudent = this.rawinStudentData.filter(stu => stu.type === '本科生')
        console.log(this.inStudent)
        this.ingStudent = this.rawinStudentData.filter(stu => stu.type === '研究生')
        console.log(this.ingStudent)
        this.inbStudent = this.rawinStudentData.filter(stu => stu.type === '博士生')
      })
    } catch (error) {
      console.error('Failed to fetch student_lived data:', error)
    }
    try {
      const response = await statStudentByedu() // 调用API
      this.rawunStudentDdata = response.data // 存储原始数据
      if (this.rawunStudentDdata) {
        this.unStudent = this.rawunStudentDdata.filter(stu => stu.type === '本科生')
        this.ungStudent = this.rawunStudentDdata.filter(stu => stu.type === '研究生')
      }
    } catch (error) {
      console.error('Failed to fetch student_unlived data:', error)
    }
    try {
      const response = await statbed() // 调用API（根据数据库改过）
      this.bedsData = response.data // 存储原始数据

      // 分离出type=A和type=B的数据
      this.typeABeds = this.bedsData.filter(bed => bed.type === '本科生')
      this.typeBBeds = this.bedsData.filter(bed => bed.type === '研究生')
      this.typeCBeds = this.bedsData.filter(bed => bed.type === '博士生')
      console.log('2', this.typeCBeds)
    } catch (error) {
      console.error('Failed to fetch bed usage data:', error)
    }
    // 添加了本科生与研究生空闲床位的计算
    try {
      if (this.typeABeds[0].number - this.inStudent[0].number > 0) {
        this.underBed = this.typeABeds[0].number - this.inStudent[0].number
      }
      if (this.typeBBeds[0].number - this.ingStudent[0].number > 0) {
        this.freeBed = this.typeBBeds[0].number - this.ingStudent[0].number
      }
    } catch (error) {
      console.error('Failed to count bed free data:', error)
    }
  }
}
</script>
<style scoped>
.title1 {
    color: #808080;
    font-size: 16px;
    font-face: Source Han Sans CN;
    font-weight: 700;
    letter-spacing: 0;
    padding: 16px;
    line-height: 60px;
}

.title2 {
    color: #1a1a1a;
    font-size: 16px;
    font-face: Source Han Sans CN;
    font-weight: 700;
    letter-spacing: 0;
}

.card-container1 {
    width: 70%;
    height: 943px;
    border-radius: 6px;
    background: #fff;
}
.card-container2{
    width: 30%;
    margin-left: 10px;
    height: 943px;
    border-radius: 6px;
    background: #fff;
}
.container{
    display: flex;
}
.sub-card1{
    width: 455px;
    height: 294px;
    background: transparent;
    background-image: url("../../../../assets/images/total/qq.png");
}
.sub-card2{
    width: 455px;
    height: 294px;
    background: transparent;
    background-image: url("../../../../assets/images/total/nm.png");
}
.sub-card3{
    width: 455px;
    height: 294px;
    background: transparent;
    background-image: url("../../../../assets/images/total/nd.png");
}
.c {
    background-image: url("../../../../assets/images/git/99.png");
}
.table1{
    width: 1121px;
    height: 943px;
    border-radius: 6px;
    background: #fff;
}
</style>
